package network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket socket = null;

    TcpEchoServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        //创建线程池
        ExecutorService service = Executors.newCachedThreadPool();
        while (true) {
            //不断建立连接
            Socket clientSocket = socket.accept();
            //不要忘记关闭clientSocket, 防止文件泄露
            //对客户端的请求进行处理
            service.submit(new Runnable(){
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n", clientSocket.getInetAddress(), clientSocket.getPort());
        //不断进行获取和写入
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //客户端不再输入
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //获取客户端的输入
                String receive = scanner.next();
                String request = process(receive);
                PrintWriter printWriter = new PrintWriter(outputStream);
                //这里并不是打印到控制台而是写入流对象
                printWriter.println(request);
                //对流对象的写入进行及时的冲洗
                printWriter.flush();
                System.out.printf("[%s:%d] receive=%s request=%s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(),
                        receive, request);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }
    private String process(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(1314);
        server.start();
    }
}
